import axios from 'axios'
import Config from '@/config'
import wfc from '@/wfc/client/wfc'
import { getItem } from '@/ui/util/storageHelper'

const TIME_OUT = 1000 * 180

const http = axios.create({
  baseURL: Config.APP_SERVER,
  timeout: TIME_OUT,
  withCredentials: true,
  headers: {
    'common-params': JSON.stringify({
      appKey: '574183392d914549b7cd8de75d284e2b',
    }),
    'content-type': 'application/json',
  },
})

// ---- 请求拦截 ----
http.interceptors.request.use(
  (config) => {
    // Token验证
    const token = getItem('token')

    if (token) {
      config.headers['app-service-token'] = token
    }

    return config
  },
  (err) => {
    return Promise.reject(err)
  }
)

// ---- 响应拦截 ----
http.interceptors.response.use(
  (res) => {
    return res
  },
  (err) => {
    return Promise.reject(err)
  }
)

// 封装增删改查方法
const request = {}
const methods = ['get', 'post', 'put', 'delete']

methods.forEach((method) => {
  request[method] = (url = '', params = {}, headers = {}) => {
    return new Promise((resolve, reject) => {
      const options = {
        method: method === 'del' ? 'delete' : method,
        url,
        headers,
      }

      params = {
        platform: 3,
        clientId: wfc.getClientId(),
        ...params,
      }

      options[method == 'get' ? 'params' : 'data'] = params

      http(options)
        .then((res) => {
          const { code, message } = res.data

          if (code !== 200) {
            $message.error(message || '请求失败，请重试')
          }

          resolve(res.data)
        })
        .catch((err) => {
          const res = err?.response?.data || err
          const { code, message } = res

          if (code !== 200) {
            $message.error(message || '请求失败，请重试')
          }

          reject(res)
        })
    })
  }
})

export default request
